layui.define([ 'form', 'laydate', 'table' ,'layer'], function(exports) {
    var form = layui.form;
    var laydate = layui.laydate;
    var table = layui.table;
    var finTransactionTable = null;
    var $ = layui.jquery;
    var layer1 = layui.layer;
    var view ={
        init:function(){
            this.initTable();
            this.initSearchForm();
            this.initToolBar();
            window.dataReload = function(){
                Lib.doSearchForm($("#searchForm"),finTransactionTable)
            }
        },
        initTable:function(){
            finTransactionTable = table.render({
                elem : '#finTransactionTable',
                height : Lib.getTableHeight(0),
                cellMinWidth: 100,
                method : 'post',
                url : Common.ctxPath + '/trans/finTransaction/list.json' // 数据接口
                ,page : Lib.tablePage // 开启分页
                ,limit : 10,
                cols : [ [ // 表头
                    {
                        type : 'checkbox',
                        fixed:'left',
                    },
                {

                    field : 'transactionId',
                        title : '交易id',
                    fixed:'left',
                        width : 300,
                },
                {

                    field : 'userId',
                        title : '用户id',
                    width : 300,
                },
                    {

                        field : 'phone',
                        title : '手机号',
                        width : 140,
                    },
                {

                    field : 'orderId',
                        title : '订单id',
                    width : 150,
                },
                {

                    field : 'orderNo',
                    title : '订单编号',
                    width : 150,
                },
                {

                    field : 'orderName',
                        title : '订单类型',
                    width : 120,
                },
                {

                    field : 'payMethodText',
                        title : '支付类型',
                },
                {

                    field : 'totalMoney',
                        title : '交易金额(元)',
                    width : 130,
                    sort:true,
                    templet:function (d) {
                        return d.totalMoney/100;
                    }
                },
                {

                    field : 'payFlagText',
                        title : '支付状态',
                },
                {

                    field : 'createTime',
                        title : '创建时间',
                    sort:true,
                    width : 170,
                },
                {

                    field : 'payTime',
                        title : '支付时间',
                    sort:true,
                    width : 170,
                },
                {

                    field : 'refundTime',
                        title : '退款时间',
                    sort:true,
                    width : 170,
                },
                {

                    field : 'channelName',
                        title : '来源渠道',
                }

        ] ]

        });
            table.on('sort(finTransactionTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                console.log(obj.field); //当前排序的字段名
                console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
                console.log(this); //当前排序的 th 对象

                //尽管我们的 table 自带排序功能，但并没有请求服务端。
                //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
                table.reload('finTransactionTable', {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                    ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        field: obj.field //排序字段
                        ,order: obj.type //排序方式
                    }
                });
            });
            table.on('checkbox(finTransactionTable)', function(obj){
                var finTransaction = obj.data;
                if(obj.checked){
                    //按钮逻辑Lib.buttonEnable()
                }else{

                }
            })
        },

        initSearchForm:function(){
            Lib.initSearchForm( $("#searchForm"),finTransactionTable,form);
        },
        initToolBar:function(){
            toolbar = {
                refund : function() { // 获取选中数据
                    var data = Common.getOneFromTable(table,"finTransactionTable");
                    if(data==null){
                        return ;
                    }
                    if (data.payFlag!=2) {
                        Common.info("该单据不是已支付状态，不能退款。");
                        return;
                    }
                    Common.postHtml("/trans/finTransaction/refund.do",{transactionId:data.transactionId},function(rsp){
                        layer.open({
                            type:0,
                            title:"退款",
                            content:rsp,
                            area: "477px",
                            btn:["退款","取消"],
                            yes:function(index, layero) {
                                refundMoney();
                            },
                            btn2:function(index, layero) {
                                layer.close(index);
                            }
                        });
                    });
                },
                edit : function() { // 获取选中数目
                    var data = Common.getOneFromTable(table,"finTransactionTable");
                    if(data==null){
                        return ;
                    }
                    var url = "/trans/finTransaction/edit.do?transactionId="+data.transactionId;
                    Common.openDlg(url,"交易管理>"+data.transactionId+">编辑");
                },
                del : function() {
                    layui.use(['del'], function(){
                        var delView = layui.del
                        delView.delBatch();
                    });
                }
            ,
                exportDocument : function() {
                    layui.use([ 'finTransactionApi' ], function() {
                        var finTransactionApi = layui.finTransactionApi
                        Common.openConfirm("确认要导出这些FinTransaction数据?", function() {
                            finTransactionApi.exportExcel($("#searchForm"), function(fileId) {
                                Lib.download(fileId);
                            })
                        })
                    });
                },
                importDocument:function(){
                    var uploadUrl = Common.ctxPath+"/trans/finTransaction/excel/import.do";
                    //模板,
                    var templatePath= "/trans/finTransaction/finTransaction_upload_template.xls";
                    //公共的简单上传文件处理
                    var url = "/core/file/simpleUpload.do?uploadUrl="+uploadUrl+"&templatePath="+templatePath;
                    Common.openDlg(url, "FinTransaction管理>上传");
                },
                login:function () {
                    var data = Common.getOneFromTable(table,"finTransactionTable");
                    if(data==null){
                        return ;
                    }
                    var origin = window.location.origin
                    var customerId = data.userId
                    console.dir(data);
                    var url="";
                    if(origin.indexOf("qitian.51sdx.com")>=0){
                        url = "http://m.51sdx.com/p/qtwlh5s?customerId="+customerId;
                    }else if(origin.indexOf("cms.51sdx.com")>=0){
                        if(data.channel  == "GSW001"){
                            url = "http://m.51sdx.com/p/gswh5?customerId="+customerId;
                        }else{
                            url = "http://m.51sdx.com/p/choice?customerId="+customerId;
                        }
                    }else{
                        url = "http://m.51sdx.com/t/choice?customerId="+customerId;
                    }
                    // window.open(url);

                    console.log(url);
                    CopyToClipboard(url);
                    // alert("已复制到剪贴板");
                }
        };
            $('.ext-toolbar').on('click', function() {
                var type = $(this).data('type');
                toolbar[type] ? toolbar[type].call(this) : '';
            });
        }
    }


    function CopyToClipboard (input) {
        var textToClipboard = input;

        var success = true;
        if (window.clipboardData) { // Internet Explorer
            window.clipboardData.setData ("Text", textToClipboard);
        }
        else {
            // create a temporary element for the execCommand method
            var forExecElement = CreateElementForExecCommand (textToClipboard);

            /* Select the contents of the element
                (the execCommand for 'copy' method works on the selection) */
            SelectContent (forExecElement);

            var supported = true;

            // UniversalXPConnect privilege is required for clipboard access in Firefox
            try {
                if (window.netscape && netscape.security) {
                    netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
                }

                // Copy the selected content to the clipboard
                // Works in Firefox and in Safari before version 5
                success = document.execCommand ("copy", false, null);
            }
            catch (e) {
                success = false;
            }

            // remove the temporary element
            document.body.removeChild (forExecElement);
        }

        if (success) {
            Common.info ("复制成功");
        }
        else {
            Common.info ("您的浏览器不允许剪贴板访问！");
        }
    }

    function CreateElementForExecCommand (textToClipboard) {
        var forExecElement = document.createElement ("div");
        // place outside the visible area
        forExecElement.style.position = "absolute";
        forExecElement.style.left = "-10000px";
        forExecElement.style.top = "-10000px";
        // write the necessary text into the element and append to the document
        forExecElement.textContent = textToClipboard;
        document.body.appendChild (forExecElement);
        // the contentEditable mode is necessary for the  execCommand method in Firefox
        forExecElement.contentEditable = true;

        return forExecElement;
    }

    function SelectContent (element) {
        // first create a range
        var rangeToSelect = document.createRange();
        rangeToSelect.selectNodeContents(element);

        // select the contents
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(rangeToSelect);
    }


    exports('index',view);

});
